//
//  ShopcartOrderViewController.m
//  B2C
//
//  Created by 李小龙 on 2017/8/10.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "ShopcartOrderViewController.h"
#import "AddressChooseViewController.h"
#import "AddressChooserTableViewCell.h"
#import "ShopcartOrderTableViewCell.h"
#import "CouponModel.h"
#import "CouponViewController.h"
#import "PayView.h"
#import "PayStatusViewController.h"
#import <AlipaySDK/AlipaySDK.h>

@interface ShopcartOrderViewController ()<UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate,UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    AddressChooserTableViewCell *_addressV;
}

@property (nonatomic, strong) UIImagePickerController *imagePickerController;
@property (nonatomic, strong) PayView *payView;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *addressView;
@property (weak, nonatomic) IBOutlet UIButton *addressButton;
@property (weak, nonatomic) IBOutlet UIImageView *rightArrowImage;

@property (strong, nonatomic) UITextField *nameTextField;   // 发票 名
@property (strong, nonatomic) UITextField *numberTextField; // 发票 税号
@property (strong, nonatomic) SZTextView *remarksTextView;  // 备注
@property (strong, nonatomic) UITextField * IDCardNameTextField;    // 身份证姓名
@property (strong, nonatomic) UITextField * IDCardNumberTextField;  // 身份证号
@property (strong, nonatomic) UIImage *IDCardFrontImage;    // 身份证正面
@property (strong, nonatomic) UIImage *IDCardBackImage;     // 身份证背面
@property (copy, nonatomic) NSString *IDCardFrontURL;       // 身份证正面链接
@property (copy, nonatomic) NSString *IDCardBackURL;        // 身份证背面链接
@property (assign, nonatomic) ShopcartOrderClickType IDCardImageType;

@property (weak, nonatomic) IBOutlet UILabel *totalCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;

@property (nonatomic, copy) NSString *priceStr;     // 总价
@property (nonatomic, copy) NSString *postageStr;   // 邮费
@property (nonatomic, copy) NSString *receiptType;  // 0不开发票 1普通发票
@property (nonatomic, copy) NSString *receiptTitle; // 0个人 1企业
@property (nonatomic, assign) BOOL isScope;         // 是否在配送范围内

@end

@implementation ShopcartOrderViewController
#pragma mark - Get
- (NSMutableArray<ShopcartClassifyModel *> *)tableArray {
    if (!_tableArray) {
        _tableArray = [[NSMutableArray alloc] init];
    }
    return _tableArray;
}
- (UIImagePickerController *)imagePickerController {
    if (!_imagePickerController) {
        //初始化图片选择器
        _imagePickerController = [[UIImagePickerController alloc]init];
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
    }
    return _imagePickerController;
}
- (PayView *)payView {
    if (!_payView) {
        _payView = [[PayView alloc] initWithFrame:Screen];
    }
    return _payView;
}
#pragma mark - IBAction
- (IBAction)chooseAddressButtonAction:(id)sender {
    AddressChooseViewController *chooseVC = [[AddressChooseViewController alloc] init];
    chooseVC.selectModel = self.selectModel;
    chooseVC.isShopcartNew = YES;
    
    __block typeof(self) blockSelf = self;
    chooseVC.block = ^(AddressModel *chooseModel) {
        blockSelf.selectModel = chooseModel;
        [blockSelf updateUI];
        if (blockSelf.selectModel) {
            [blockSelf getPostageNetData];
        }
    };
    [self.navigationController pushViewController:chooseVC animated:YES];
}

- (IBAction)submitButtonAction:(id)sender {
    
    if (!self.selectModel) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请选择收货地址" animated:YES];
        return;
    }
    if (!self.isScope) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请重新选择收货地址" animated:YES];
        return;
    }
    if ([self.receiptType isEqualToString:@"1"]) {
        if (!TextIsNotNil(self.receiptTitle)) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请选择发票抬头" animated:YES];
            return;
        }
        if (!TextIsNotNil(self.nameTextField.text)) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请填写姓名" animated:YES];
            return;
        }
        if ([self.receiptTitle isEqualToString:@"1"]) {
            if (!TextIsNotNil(self.numberTextField.text)) {
                [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请填写纳税人识别号" animated:YES];
                return;
            }
        }
    }
    if (self.isHaveWorldwide) {
        if (!TextIsNotNil(self.IDCardNameTextField.text)) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请填写真实姓名" animated:YES];
            return;
        }
        if (![LXLIsPhoneNumber judgeIdentityStringValid:self.IDCardNumberTextField.text]) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请填写正确的身份证号" animated:YES];
            return;
        }
        if (!self.IDCardFrontImage) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请上传身份证正面照片" animated:YES];
            return;
        }
        if (!self.IDCardBackImage) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请上传身份证反面照片" animated:YES];
            return;
        }
        if (!TextIsNotNil(self.IDCardFrontURL)) {
            [self uploadImage:self.IDCardFrontImage success:^(NSString *imageUrl) {
                self.IDCardFrontURL = imageUrl;
                [self submitButtonAction:nil];
            }];
            return;
        }
        if (!TextIsNotNil(self.IDCardBackURL)) {
            [self uploadImage:self.IDCardBackImage success:^(NSString *imageUrl) {
                self.IDCardBackURL = imageUrl;
                [self submitButtonAction:nil];
            }];
            return;
        }
    }
    
    if (self.type == ShopcartOrderTypeIntegral) {
        // 积分商品支付
        [self uploadOrder:@"-1"];
    } else {
        // 弹出支付方式
        [self.payView showView];
    }
}

#pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"确认订单";
    self.isScope = NO;
    self.postageStr = @"0";
    self.selectModel = [UserInfo shareInstance].user.defaultAddress;
    
//    if (self.type == ShopcartOrderTypeIntegral) {
//        self.receiptType = @"0"; // 不开发票
//    } else {
//        self.receiptType = @"1"; // 普通发票
//    }
    self.receiptType = @"0"; // 不开发票
    self.receiptTitle = @"0"; // 个人
    
    __block typeof(self) blockSelf = self;
    self.payView.block = ^(NSString *payType, NSString *rechargeStr) {
        [blockSelf uploadOrder:payType];
    };
    
    [self updateTableView];
    [self getPriceNetData];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hiddenShadowImage:NO];
    
    if (self.selectModel) {
        [self getPostageNetData];
    }
    
    [self updateUI];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    [super keyboardWillShow:notification];
//    if (self.nameTextField.isFirstResponder || self.numberTextField.isFirstResponder) {
//        [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height-self.tableView.height+_keyboardEndFrame.size.height-55) animated:YES];
//    }
}
- (void)keyboardWillHide:(NSNotification *)notification {
    [super keyboardWillHide:notification];
    if (self.tableView.contentSize.height < self.tableView.height) {
        [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    } else if ((self.tableView.contentOffset.y+self.tableView.height) > self.tableView.contentSize.height) {
        [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height-self.tableView.height) animated:YES];
    }
}

#pragma mark - 网络请求
- (NSString *)getScidsWith:(ShopcartClassifyModel *)shopcartModel {
    NSString *scids = @"";
    for (NSInteger j = 0; j < shopcartModel.shopcart.count; j++) {
        ShopcartModel *model = shopcartModel.shopcart[j];
        if (!TextIsNotNil(scids)) {
            scids = model.scid;
        } else {
            if (TextIsNotNil(model.scid)) {
                scids = [NSString stringWithFormat:@"%@,%@",scids,model.scid];
            }
        }
    }
    return scids;
}
- (NSString *)getScids {
    NSString *scids = @"";
    for (NSInteger i = 0; i < self.tableArray.count; i++) {
        ShopcartClassifyModel *shopcartModel = self.tableArray[i];
        for (NSInteger j = 0; j < shopcartModel.shopcart.count; j++) {
            ShopcartModel *model = shopcartModel.shopcart[j];
            if (!TextIsNotNil(scids)) {
                scids = model.scid;
            } else {
                if (TextIsNotNil(model.scid)) {
                    scids = [NSString stringWithFormat:@"%@,%@",scids,model.scid];
                }
            }
        }
    }
    return scids;
}
- (NSString *)getGaids {
    if (TextIsNotNil(self.gaids)) {
        return self.gaids;
    }
    NSString *gaids = @"";
    for (NSInteger i = 0; i < self.tableArray.count; i++) {
        ShopcartClassifyModel *shopcartModel = self.tableArray[i];
        for (NSInteger j = 0; j < shopcartModel.shopcart.count; j++) {
            ShopcartModel *model = shopcartModel.shopcart[j];
            if (!TextIsNotNil(gaids)) {
                gaids = model.gaid;
            } else {
                if (TextIsNotNil(model.gaid)) {
                    gaids = [NSString stringWithFormat:@"%@,%@",gaids,model.gaid];
                }
            }
        }
    }
    return gaids;
}
- (NSString *)getNumbers {
    if (TextIsNotNil(self.numbers)) {
        return self.numbers;
    }
    NSString *numbers = @"";
    for (NSInteger i = 0; i < self.tableArray.count; i++) {
        ShopcartClassifyModel *shopcartModel = self.tableArray[i];
        for (NSInteger j = 0; j < shopcartModel.shopcart.count; j++) {
            ShopcartModel *model = shopcartModel.shopcart[j];
            if (i == 0 && j == 0) {
                numbers = model.number;
            } else {
                numbers = [NSString stringWithFormat:@"%@,%@",numbers,model.number];
            }
        }
    }
    return numbers;
}
- (NSString *)getCids {
    NSString *cids = @"";
    for (NSInteger i = 0; i < self.tableArray.count; i++) {
        ShopcartClassifyModel *shopcartModel = self.tableArray[i];
        for (NSInteger j = 0; j < shopcartModel.shopcart.count; j++) {
            if (shopcartModel.couponModel) {
                if (!TextIsNotNil(cids)) {
                    cids = shopcartModel.couponModel.cid;
                    
                } else if (TextIsNotNil(shopcartModel.couponModel.cid)) {
                    cids = [NSString stringWithFormat:@"%@,%@",cids,shopcartModel.couponModel.cid];
                }
            }
            
//            if (i == 0 && j == 0) {
//                if (shopcartModel.couponModel) {
//                    cids = shopcartModel.couponModel.cid;
//                }
//            } else {
//                if (shopcartModel.couponModel) {
//                    cids = [NSString stringWithFormat:@"%@,%@",cids,shopcartModel.couponModel.cid];
//                } else {
//                    cids = [NSString stringWithFormat:@"%@,%@",cids,@""];
//                }
//            }
        }
    }
    return cids;
}
- (NSString *)getFcids {
    NSString *fcids = @"";
    for (NSInteger i = 0; i < self.tableArray.count; i++) {
        ShopcartClassifyModel *shopcartModel = self.tableArray[i];
        double classTotal = 0;
        for (ShopcartModel *model in shopcartModel.shopcart) {
            classTotal += model.gprice.doubleValue*model.number.integerValue;
        }
        
        for (NSInteger j = 0; j < shopcartModel.shopcart.count; j++) {
            if (!shopcartModel.couponModel) {
                if (!TextIsNotNil(fcids)) {
                    for (GoodsFullCut *cutModel in shopcartModel.fullcut) {
                        if (classTotal > cutModel.fcfull.doubleValue) {
                            fcids = cutModel.fcid;
                            break;
                        }
                    }
                    
                } else {
                    if (shopcartModel.fullcut.count > 0) {
                        for (GoodsFullCut *cutModel in shopcartModel.fullcut) {
                            if (classTotal > cutModel.fcfull.doubleValue && TextIsNotNil(cutModel.fcid)) {
                                fcids = [NSString stringWithFormat:@"%@,%@",fcids,cutModel.fcid];
                                break;
                            }
                        }
                    }
                }
            }
            
            
//            if (i == 0 && j == 0) {
//                if (!shopcartModel.couponModel) {
//                    for (GoodsFullCut *cutModel in shopcartModel.fullcut) {
//                        if (classTotal > cutModel.fcfull.doubleValue) {
//                            fcids = cutModel.fcid;
//                            break;
//                        }
//                    }
//                }
//            } else {
//                if (!shopcartModel.couponModel && shopcartModel.fullcut.count > 0) {
//                    for (GoodsFullCut *cutModel in shopcartModel.fullcut) {
//                        if (classTotal > cutModel.fcfull.doubleValue) {
//                            fcids = [NSString stringWithFormat:@"%@,%@",fcids,cutModel.fcid];
//                            break;
//                        }
//                    }
//                } else {
//                    fcids = [NSString stringWithFormat:@"%@,%@",fcids,@""];
//                }
//            }
        }
    }
    return fcids;
}
- (NSString *)getNotes {
    NSString *notes = @"";
    for (NSInteger i = 0; i < self.tableArray.count; i++) {
        ShopcartClassifyModel *shopcartModel = self.tableArray[i];
        for (NSInteger j = 0; j < shopcartModel.shopcart.count; j++) {
            ShopcartModel *model = shopcartModel.shopcart[j];
            if (i == 0 && j == 0) {
                notes = TextIsNotNil(model.note)?model.note:@"";
            } else {
                notes = [NSString stringWithFormat:@"%@,%@",notes,TextIsNotNil(model.note)?model.note:@""];
            }
        }
    }
    return notes;
}
- (void)uploadOrder:(NSString *)payType {
    //MARK:测试 提交订单
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    NSString *url = @"";
    switch (self.type) {
        case ShopcartOrderTypeCart:
        {
            [dic setObject:[self getScids] forKey:@"scids"];
            [dic setObject:[self getNotes] forKey:@"ogremark"];
            //MARK:测试 非必填参数cid(优惠券id) fcid(满减id)
            [dic setObject:[self getCids] forKey:@"cids"];
            [dic setObject:[self getFcids] forKey:@"fcids"];
            
            url = URL_Shopcart_Order;
        } break;
        case ShopcartOrderTypeGoods:
        {
            [dic setObject:self.tableArray.firstObject.shopcart.firstObject.gaid forKey:@"gaid"];
            [dic setObject:self.tableArray.firstObject.shopcart.firstObject.number forKey:@"number"];
            NSString *note =  TextIsNotNil(self.tableArray.firstObject.shopcart.firstObject.note)?self.tableArray.firstObject.shopcart.firstObject.note:@"";
            [dic setObject:note forKey:@"ogremark"];
            [dic safeSetObject:self.fields forKey:@"fields"]; //立即购买，添加fields字段
            [dic safeSetObject:self.tableArray.firstObject.shopcart.firstObject.gid forKey:@"gid"];
            
            //MARK:测试 非必填参数cid(优惠券id) fcid(满减id)
            [dic setObject:[self getCids] forKey:@"cid"];
            [dic setObject:[self getFcids] forKey:@"fcid"];
            
            url = URL_Goods_Order;
        } break;
        case ShopcartOrderTypeNearby:
        {
            [dic setObject:[self getGaids] forKey:@"gaids"];
            [dic setObject:[self getNumbers] forKey:@"numbers"];
            [dic setObject:[self getNotes] forKey:@"ogremark"];
            
            url = URL_Shop_Goods_Order;
        } break;
        case ShopcartOrderTypeIntegral:
        {
            [dic setObject:self.tableArray.firstObject.shopcart.firstObject.gaid forKey:@"gaid"];
            [dic setObject:self.tableArray.firstObject.shopcart.firstObject.number forKey:@"number"];
            NSString *note =  TextIsNotNil(self.tableArray.firstObject.shopcart.firstObject.note)?self.tableArray.firstObject.shopcart.firstObject.note:@"";
            [dic setObject:note forKey:@"ogremark"];
            
            url = URL_Integral_Goods_Order;
        } break;
        case ShopcartOrderTypeSeckill:
        {
            [dic setObject:self.tableArray.firstObject.shopcart.firstObject.gaid forKey:@"gaid"];
            [dic setObject:self.tableArray.firstObject.shopcart.firstObject.number forKey:@"number"];
            NSString *note =  TextIsNotNil(self.tableArray.firstObject.shopcart.firstObject.note)?self.tableArray.firstObject.shopcart.firstObject.note:@"";
            [dic setObject:note forKey:@"ogremark"];
            [dic safeSetObject:self.fields forKey:@"fields"]; //立即购买，添加fields字段
            [dic safeSetObject:self.tableArray.firstObject.shopcart.firstObject.gid forKey:@"gid"];
            
            url = URL_Seckill_Goods_Order;
        } break;
        case ShopcartOrderTypeGroup:
        {
            [dic setObject:self.tableArray.firstObject.shopcart.firstObject.gaid forKey:@"gaid"];
            [dic setObject:self.tableArray.firstObject.shopcart.firstObject.number forKey:@"number"];
            NSString *note =  TextIsNotNil(self.tableArray.firstObject.shopcart.firstObject.note)?self.tableArray.firstObject.shopcart.firstObject.note:@"";
            [dic setObject:note forKey:@"ogremark"];
            
            url = URL_Group_Goods_Order;
        } break;
        case ShopcartOrderTypePurchase:
        {
            [dic setObject:self.tableArray.firstObject.shopcart.firstObject.gaid forKey:@"gaids"];
            [dic setObject:self.tableArray.firstObject.shopcart.firstObject.number forKey:@"numbers"];
            NSString *note =  TextIsNotNil(self.tableArray.firstObject.shopcart.firstObject.note)?self.tableArray.firstObject.shopcart.firstObject.note:@"";
            [dic setObject:note forKey:@"ogremark"];
            
            url = URL_Purchase_Goods_Order;
        } break;
        default:
            break;
    }
    
    
    [dic setObject:self.selectModel.daid forKey:@"daid"];
    [dic setObject:payType forKey:@"ompaytype"];
    //发票
    [dic setObject:self.receiptType forKey:@"ominvoicetype"];
    if ([self.receiptType isEqualToString:@"1"]) {
        [dic setObject:self.receiptTitle forKey:@"ominvoicerise"];
        [dic setObject:self.nameTextField.text forKey:@"ominvoicename"];
        if ([self.receiptTitle isEqualToString:@"1"]) {
            [dic setObject:self.numberTextField.text forKey:@"ominvoicenumber"];
        } else {
            [dic setObject:@"" forKey:@"ominvoicenumber"];
        }
    } else {
        [dic setObject:@"0" forKey:@"ominvoicerise"];
        [dic setObject:@"" forKey:@"ominvoicename"];
        [dic setObject:@"" forKey:@"ominvoicenumber"];
    }
    
    
    // 身份证信息
    if (self.isHaveWorldwide) {
        [dic setObject:self.IDCardNameTextField.text forKey:@"realname"];
        [dic setObject:self.IDCardNumberTextField.text forKey:@"idnumber"];
        [dic setObject:self.IDCardFrontURL forKey:@"idcardfrontendurl"];
        [dic setObject:self.IDCardBackURL forKey:@"idcardbackendurl"];
    } else {
        [dic setObject:@"" forKey:@"realname"];
        [dic setObject:@"" forKey:@"idnumber"];
        [dic setObject:@"" forKey:@"idcardfrontendurl"];
        [dic setObject:@"" forKey:@"idcardbackendurl"];
    }
    
    
    
    __block typeof(self) blockSelf = self;
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:url parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (blockSelf.type == ShopcartOrderTypeIntegral) {
            PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
            statusVC.isIntegral = YES;
            statusVC.osid = responseObject[@"data"][@"omid"];
            if ([responseObject[@"code"] isEqualToString:@"200"]) {
                statusVC.type = StatusTypePaySuccess;
            } else {
                statusVC.type = StatusTypePayFail;
            }
            [blockSelf.navigationController pushViewController:statusVC animated:YES];
            return;
        }
        
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
//            //MARK:测试 根据类型跳支付宝、微信付款
//            self.omid = @"O51503991761";
//            
//            PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
//            statusVC.omid = self.omid;
//            statusVC.type = StatusTypePaySuccess;
////            statusVC.type = StatusTypePayFail;
//            [self.navigationController pushViewController:statusVC animated:YES];
////            [self popToRootViewController];
//            return;
//            //MARK:-
            if (![responseObject[@"data"] isKindOfClass:[NSString class]]) {
//                //MARK:测试 跳转状态页
//                PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
//                //MARK:测试
//                if (TextIsNotNil(responseObject[@"data"][@"omid"])) {
//                    statusVC.osid = responseObject[@"data"][@"omid"];
//                } else {
//                    statusVC.osid = @"O51515569265";
//                }
//                //--
//                statusVC.type = StatusTypePaySuccess;
//                if (self.type == ShopcartOrderTypeIntegral) {
//                    statusVC.isIntegral = YES;
//                }
//                [blockSelf.navigationController pushViewController:statusVC animated:YES];
//                return;
                
                blockSelf.osid = responseObject[@"data"][@"omid"];
                if (blockSelf.type == ShopcartOrderTypeIntegral) {
                    //[blockSelf uploadIntegral:blockSelf.osid];
                } else {
                    NSString *omid = responseObject[@"data"][@"omid"];
                    if (blockSelf.type == ShopcartOrderTypeCart) {
                        omid = responseObject[@"data"][@"ompaynumber"];
                    }
                    [blockSelf uploadPayOrder:payType price:[NSString stringWithFormat:@"%.2f",blockSelf.priceStr.doubleValue+blockSelf.postageStr.doubleValue] omid:omid];
                }
            } else {
                [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
            }
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
- (void)uploadPayOrder:(NSString *)payType price:(NSString *)price omid:(NSString *)omid {
    NSString *payUrl;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:omid forKey:@"omid"];
    if ([payType isEqualToString:@"0"]) {
        payUrl = URL_Pay_Wechat;
    } else if ([payType isEqualToString:@"1"]) {
        payUrl = URL_Pay_Alipay;
    } else {
        payUrl = URL_Pay_Balance;
        [dic setObject:price forKey:@"price"];
    }
    
    __block typeof(self) blockSelf = self;
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:payUrl parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        if ([payType isEqualToString:@"2"]) {
            PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
            statusVC.osid = blockSelf.osid;
            if ([responseObject[@"code"] isEqualToString:@"200"]) {
                statusVC.type = StatusTypePaySuccess;
            } else {
                statusVC.type = StatusTypePayFail;
            }
            [blockSelf.navigationController pushViewController:statusVC animated:YES];
        } else if ([responseObject[@"code"] isEqualToString:@"200"]) {
            if ([payType isEqualToString:@"1"]) {
                [blockSelf uploadAlipay:responseObject[@"data"]];
            } else if ([payType isEqualToString:@"0"]) {
                [blockSelf uploadWechatPay:responseObject[@"data"]];
            }
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}

- (void)uploadAlipay:(NSString *)orderString {
    
    __weak typeof(self) weakSelf = self;
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:AppScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            //成功
            if (weakSelf.block) {
                weakSelf.block(YES);
            } else {
                PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
                statusVC.osid = weakSelf.osid;
                statusVC.type = StatusTypePaySuccess;
                
                [weakSelf.navigationController pushViewController:statusVC animated:YES];
            }
        } else {
            //[MBProgressHUD myShowHUDAddedTo:weakSelf.view labelText:@"付款失败" animated:YES];
            PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
            statusVC.osid = weakSelf.osid;
            statusVC.type = StatusTypePayFail;
            
            [weakSelf.navigationController pushViewController:statusVC animated:YES];
        }
    }];
    
}
- (void)uploadWechatPay:(NSDictionary *)parameters {
    
    if (![WXApi isWXAppInstalled]) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"没有安装微信" animated:YES];
        return;
    }
    if (![WXApi isWXAppSupportApi]) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"当前微信版本过低" animated:YES];
        return;
    }
    
    PayReq *request   = [[PayReq alloc] init];
    //request.openID    = responseObject[@"data"][@"appId"];
    request.partnerId = parameters[@"partnerid"];
    request.prepayId  = parameters[@"prepayid"];
    request.package   = @"Sign=WXPay"; //parameters[@"packagevalue"];//Sign=WXPay
    request.nonceStr  = parameters[@"noncestr"];
    request.timeStamp = [parameters[@"timestamp"] unsignedIntValue];
    request.sign      = parameters[@"sign"];
    if ([WXApi sendReq:request]) {
        NSLog(@"发送成功");
        if (self.block) {
            self.block(YES);
        }
    } else {
        NSLog(@"发送失败");
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"订单获取失败" animated:YES];
    }
}
- (void)uploadBalancePay:(NSDictionary *)parameters {
    //MARK:测试 余额支付
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:parameters[@"data"][@"omid"] forKey:@"omid"];
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    __block typeof(self) blockSelf = self;
    [MYAFNetworking POST:URL_Pay_Balance parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        
        PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
        statusVC.osid = parameters[@"data"][@"omid"];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            statusVC.type = StatusTypePaySuccess;
        } else {
            statusVC.type = StatusTypePayFail;
        }
        [blockSelf.navigationController pushViewController:statusVC animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        
        PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
        statusVC.osid = parameters[@"data"][@"omid"];
        statusVC.type = StatusTypePayFail;
        [blockSelf.navigationController pushViewController:statusVC animated:YES];
    }];
}
- (void)uploadIntegral:(NSString *)omid {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    __block typeof(self) blockSelf = self;
    [MYAFNetworking POST:URL_Integral_Goods_Payment parameters:@{@"omid":omid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        
        PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
        statusVC.osid = omid;
        statusVC.isIntegral = YES;
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            statusVC.type = StatusTypePaySuccess;
        } else {
            statusVC.type = StatusTypePayFail;
        }
        [blockSelf.navigationController pushViewController:statusVC animated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        
        PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
        statusVC.osid = omid;
        statusVC.isIntegral = YES;
        statusVC.type = StatusTypePayFail;
        [blockSelf.navigationController pushViewController:statusVC animated:YES];
    }];
}
- (void)getPriceNetData {
    NSString *url;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    
    switch (self.type) {
        case ShopcartOrderTypeGoods:
        {
            url = URL_Goods_Settlement;
            ShopcartClassifyModel *classifyModel = [self.tableArray objectAtIndex:0];
            ShopcartModel *model = [classifyModel.shopcart objectAtIndex:0];
            [dic setObject:model.gaid forKey:@"gaid"];
            [dic setObject:model.number forKey:@"number"];
            [dic safeSetObject:self.fields forKey:@"fields"];
            [dic safeSetObject:model.gid forKey:@"gid"];
        } break;
        case ShopcartOrderTypeCart:
        {
            url = URL_Shopcart_Settlement;
            [dic setObject:[self getScids] forKey:@"scids"];
        } break;
        case ShopcartOrderTypeNearby:
        {
            url = URL_Shop_Goods_Settlement;
            [dic setObject:[self getGaids] forKey:@"gaids"];
            [dic setObject:[self getNumbers] forKey:@"numbers"];
        } break;
        case ShopcartOrderTypeIntegral:
        {
            url = URL_Integral_Goods_Settlement;
            ShopcartClassifyModel *classifyModel = [self.tableArray objectAtIndex:0];
            ShopcartModel *model = [classifyModel.shopcart objectAtIndex:0];
            [dic setObject:model.gaid forKey:@"gaid"];
            [dic setObject:model.number forKey:@"number"];
        } break;
        case ShopcartOrderTypeSeckill:
        {
            url = URL_Seckill_Goods_Settlement;
            ShopcartClassifyModel *classifyModel = [self.tableArray objectAtIndex:0];
            ShopcartModel *model = [classifyModel.shopcart objectAtIndex:0];
            [dic setObject:model.gaid forKey:@"gaid"];
            [dic setObject:model.number forKey:@"number"];
            [dic safeSetObject:self.fields forKey:@"fields"];
            [dic safeSetObject:model.gid forKey:@"gid"];
        } break;
        case ShopcartOrderTypeGroup:
        {
            url = URL_Group_Goods_Settlement;
            ShopcartClassifyModel *classifyModel = [self.tableArray objectAtIndex:0];
            ShopcartModel *model = [classifyModel.shopcart objectAtIndex:0];
            [dic setObject:model.gaid forKey:@"gaid"];
            [dic setObject:model.number forKey:@"number"];
        } break;
        case ShopcartOrderTypePurchase:
        {
            url = URL_Purchase_Goods_Settlement;
            ShopcartClassifyModel *classifyModel = [self.tableArray objectAtIndex:0];
            ShopcartModel *model = [classifyModel.shopcart objectAtIndex:0];
            [dic setObject:model.gaid forKey:@"gaid"];
            [dic setObject:model.number forKey:@"number"];
        } break;
        default:
            break;
    }
    
    __block typeof(self) blockSelf = self;
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:url parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSDictionary *netDic = responseObject[@"data"];
            
            //[blockSelf.tableArray removeAllObjects];
            switch (blockSelf.type) {
                case ShopcartOrderTypeGoods:
                case ShopcartOrderTypePurchase:
                {
                    ShopcartModel *goodModel = [ShopcartModel mj_objectWithKeyValues:[netDic[@"goods"] firstObject]];
                    ShopcartClassifyModel *classifyModel = [blockSelf.tableArray objectAtIndex:0];
                    
                    [classifyModel.fullcut removeAllObjects];
                    if ([netDic[@"goods"] firstObject][@"fullcut"] && ![[netDic[@"goods"] firstObject][@"fullcut"] isEqual:[NSNull null]]) {
                        for (NSDictionary *cutDic in [netDic[@"goods"] firstObject][@"fullcut"]) {
                            GoodsFullCut *cutModel = [GoodsFullCut mj_objectWithKeyValues:cutDic];
                            [classifyModel.fullcut addObject:cutModel];
                        }
                    }
                    [classifyModel.shopcart removeAllObjects];
                    [classifyModel.shopcart addObject:goodModel];
                    
                } break;
                case ShopcartOrderTypeIntegral:
                case ShopcartOrderTypeSeckill:
                case ShopcartOrderTypeGroup:
                {
                    ShopcartModel *goodModel = [ShopcartModel mj_objectWithKeyValues:netDic[@"goods"]];
                    ShopcartClassifyModel *classifyModel = [blockSelf.tableArray objectAtIndex:0];
                    
                    [classifyModel.fullcut removeAllObjects];
                    if (netDic[@"goods"][@"fullcut"] && ![netDic[@"goods"][@"fullcut"] isEqual:[NSNull null]]) {
                        for (NSDictionary *cutDic in netDic[@"goods"][@"fullcut"]) {
                            GoodsFullCut *cutModel = [GoodsFullCut mj_objectWithKeyValues:cutDic];
                            [classifyModel.fullcut addObject:cutModel];
                        }
                    }
                    if (!TextIsNotNil(goodModel.gaid)) {
                        goodModel.gaid = classifyModel.shopcart.firstObject.gaid;
                    }
                    if (!TextIsNotNil(goodModel.number) || goodModel.number.integerValue == 0) {
                        goodModel.number = classifyModel.shopcart.firstObject.number;
                    }
                    
                    [classifyModel.shopcart removeAllObjects];
                    [classifyModel.shopcart addObject:goodModel];
                } break;
                case ShopcartOrderTypeCart:
                {
                    
                } break;
                case ShopcartOrderTypeNearby:
                {
                    ShopcartClassifyModel *classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":netDic[@"goods"]}];
                    [blockSelf.tableArray removeAllObjects];
                    [blockSelf.tableArray addObject:classifyModel];
                    [blockSelf.tableView reloadData];
                } break;
                default:
                    break;
            }
            
            // 总价
            blockSelf.priceStr = [NSString stringWithFormat:@"%.2f",[netDic[@"allprice"] floatValue]];
            [blockSelf updateUI];
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
- (void)getPostageNetData {
    if (self.type != ShopcartOrderTypeNearby) {
        NSString *url;
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:self.selectModel.pid forKey:@"pid"];
        if (self.type == ShopcartOrderTypeCart) {
            url = URL_Get_FreeShipping_Shopcart;
            [dic setObject:[self getScids] forKey:@"scids"];
        } else {
            url = URL_Get_FreeShipping;
            ShopcartClassifyModel *classifyModel = [self.tableArray objectAtIndex:0];
            ShopcartModel *model = [classifyModel.shopcart objectAtIndex:0];
            [dic setObject:model.gid forKey:@"gid"];
            [dic setObject:model.number forKey:@"number"];
        }
        
        /*
         NSMutableArray *tempGoodsArr = [[NSMutableArray alloc] init];
         NSMutableArray *tempSuidArr = [[NSMutableArray alloc] init];
         for (ShopcartClassifyModel *classModel in self.tableArray) {
         for (ShopcartModel *model in classModel.shopcart) {
         [tempGoodsArr addObject:model];
         if (![tempSuidArr containsObject:model.suid]) {
         NSMutableDictionary *suidDic = [[NSMutableDictionary alloc] init];
         [suidDic setObject:model.suid forKey:@"suid"];
         [suidDic setObject:[[NSMutableArray alloc] init] forKey:@"list"];
         [tempSuidArr addObject:suidDic];
         }
         }
         }
         for (NSMutableDictionary *tempDic in tempSuidArr) {
         for (ShopcartModel *model in tempGoodsArr) {
         if ([model.suid isEqualToString:tempDic[@"suid"]]) {
         [tempDic[@"list"] addObject:model];
         }
         }
         }
         NSString *suids, *gweights;
         for (NSMutableDictionary *tempDic in tempSuidArr) {
         double allWeight = 0;
         for (ShopcartModel *model in tempDic[@"list"]) {
         allWeight += model.gweight.doubleValue * model.number.integerValue;
         }
         if ([tempDic isEqual:tempSuidArr.firstObject]) {
         suids = tempDic[@"suid"];
         gweights = [NSString stringWithFormat:@"%f",allWeight];
         } else {
         suids = [NSString stringWithFormat:@"%@,%@",suids,tempDic[@"suid"]];
         gweights = [NSString stringWithFormat:@"%@,%f",gweights,allWeight];
         }
         }
         [dic setObject:suids forKey:@"suids"];
         [dic setObject:gweights forKey:@"gweights"];
         */
        __block typeof(self) blockSelf = self;
        [MYAFNetworking POST:url parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
            //[MBProgressHUD hideHUDForView:self.view animated:YES];
            if ([responseObject[@"code"] isEqualToString:@"200"]) {
                blockSelf.isScope = YES;
                NSDictionary *netDic = responseObject[@"data"];
                if (TextIsNotNil(netDic[@"freeshipping"])) {
                    blockSelf.postageStr = [NSString stringWithFormat:@"%.2f",[netDic[@"freeshipping"] doubleValue]];
                }
                [blockSelf updateUI];
                [blockSelf.tableView reloadData];
            } else {
                blockSelf.isScope = NO;
                [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
            blockSelf.isScope = NO;
            //[MBProgressHUD hideHUDForView:self.view animated:YES];
            [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
        }];
    }
}
#pragma mark - action
- (void)updateTableView {
    [self.tableView clearExtendCellLine];
}
- (void)updateUI {
    if (self.selectModel) {
        [self.addressButton setTitle:@"" forState:UIControlStateNormal];
        if (!_addressV) {
            _addressV = [[[NSBundle mainBundle] loadNibNamed:@"AddressChooserTableViewCell" owner:self options:nil] firstObject];
        }
        [_addressV setFrame:CGRectMake(0, 0, ScreenWidth-8-13, self.addressView.height)];
        // 选中按钮
        _addressV.selectBtnWLayout.constant = 0;
        [_addressV.selectButton setHidden:YES];
        // 收货人姓名
        [_addressV.nameLabel setText:self.selectModel.daname];
        // 手机号
        [_addressV.phoneLabel setText:[LXLIsPhoneNumber phoneNumber:self.selectModel.datel]];
        // 详细地址
        [_addressV.addressLabel setText:[NSString stringWithFormat:@"%@ %@ %@ %@",self.selectModel.pname,self.selectModel.cname,self.selectModel.aname,self.selectModel.daaddress]];
        // 是否默认
        if (!self.selectModel.isdefault) {
            //_addressV.defaultWLayout.constant = 0;
            [_addressV.defaultLabel setHidden:YES];
        } else {
            //_addressV.defaultWLayout.constant = 34.0;
            [_addressV.defaultLabel setHidden:NO];
        }
        
        [self.addressView insertSubview:_addressV.contentView belowSubview:self.addressButton];
        
        [_addressV layoutIfNeeded];
    } else {
        [self.addressButton setTitle:@"您还没有收货地址，点击这里去创建" forState:UIControlStateNormal];
        
//        [self.addressView removeFromSuperview];
    }
    
    // 计算优惠后价格 不用mjallprice了,总商品数
    NSInteger totalCount = 0;
    double totalPrice = 0, subPrice = 0;
    for (ShopcartClassifyModel *shopModel in self.tableArray) {
        double classTotal = 0, classSubTotal = 0;
        for (ShopcartModel *model in shopModel.shopcart) {
            if (self.type == ShopcartOrderTypeIntegral) {
                classTotal += model.gintegral.integerValue*model.number.integerValue;
            } else {
                if (self.type == ShopcartOrderTypeSeckill) {
                    classTotal += model.gseckillprice.doubleValue*model.number.integerValue;
                } else {
                    classTotal += model.gprice.doubleValue*model.number.integerValue;
                }
            }
            totalCount += model.number.integerValue;
        }
        if (shopModel.couponModel) {
            classSubTotal += shopModel.couponModel.creduce.doubleValue;
        } else {
            for (GoodsFullCut *cutModel in shopModel.fullcut) {
                if (classTotal > cutModel.fcfull.doubleValue) {
                    classSubTotal = cutModel.fccut.doubleValue;
                    break;
                }
            }
        }
        
        totalPrice += classTotal;
        subPrice += classSubTotal;
    }
    
    if (self.type == ShopcartOrderTypeIntegral) {
        [self.totalTitleLabel setText:@"需积分："];
        self.priceStr = [NSString stringWithFormat:@"%ld",(long)(totalPrice-subPrice)];
        [self.totalPriceLabel setText:[NSString stringWithFormat:@"%ld",self.priceStr.integerValue]];
    } else {
        self.priceStr = [NSString stringWithFormat:@"%.2f",totalPrice-subPrice];
        [self.totalPriceLabel setText:[NSString stringWithFormat:@"%.2f",self.priceStr.doubleValue+self.postageStr.doubleValue]];
        
        [self.payView.priceLabel setText:[NSString stringWithFormat:@"¥%.2f",self.priceStr.doubleValue+self.postageStr.doubleValue]];
    }
    
    [self.totalCountLabel setText:[NSString stringWithFormat:@"共%ld件商品",totalCount]];
}
- (void)receiptButtonAction {
    // 选择发票类型
    [self showAlertWithTitleArray:@[@"不开发票",@"普通发票",@"取消"] title:nil message:nil alertStyle:UIAlertControllerStyleActionSheet];
    __block typeof(self) blockSelf = self;
    self.alertBlock = ^(NSString *actionTitle) {
        if (![actionTitle isEqualToString:@"取消"]) {
            if ([actionTitle isEqualToString:@"不开发票"]) {
                blockSelf.receiptType = @"0";
            }
            if ([actionTitle isEqualToString:@"普通发票"]) {
                blockSelf.receiptType = @"1";
            }
            [blockSelf.tableView reloadData];
        }
    };
}
- (void)enterpriseButtonAction {
    // 企业
    self.receiptTitle = @"1";
    [self.tableView reloadData];
}
- (void)personalButtonAction {
    // 个人
    self.receiptTitle = @"0";
    [self.tableView reloadData];
}
- (void)chooseIDCardImage:(ShopcartOrderClickType)type {
    self.IDCardImageType = type;
    
    __weak typeof(self) weakSelf = self;
    
    [self showAlertWithTitleArray:@[@"拍照",@"相册",@"取消"] title:nil message:nil alertStyle:UIAlertControllerStyleActionSheet];
    self.alertBlock = ^(NSString *actionTitle) {
        if ([actionTitle isEqualToString:@"拍照"]) {
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                [MBProgressHUD myShowHUDAddedTo:weakSelf.view labelText:@"不支持摄像头,请查看摄像权限！" animated:YES];
                return;
            }
            
            weakSelf.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [weakSelf presentViewController:weakSelf.imagePickerController animated:YES completion:^{
                //
            }];
        }
        if ([actionTitle isEqualToString:@"相册"]) {
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                [MBProgressHUD myShowHUDAddedTo:weakSelf.view labelText:@"图片库不可用,请查看隐私权限！" animated:YES];
                return;
            }
            weakSelf.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [weakSelf presentViewController:weakSelf.imagePickerController animated:YES completion:^{
                
            }];
        }
        
    };
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.tableArray.count > 0) {
        return self.tableArray.count+3;
    }
    return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger classifyCount = self.tableArray.count;
    if (section == classifyCount) {
        // 邮费
        return 1;
    } else if (section == classifyCount+1) {
        // 发票
        if (self.type == ShopcartOrderTypeIntegral) {
            return 0;
        }
        if ([self.receiptType isEqualToString:@"0"]) { // 不开发票
            return 1;
        }
        if ([self.receiptTitle isEqualToString:@"0"]) { // 个人
            return 3;
        }
        return 4;
    } else if (section == classifyCount+2) {
        // 身份证
        if (self.isHaveWorldwide) {
            return 3;
        }
        return 0;
    } else {
        // 商品+备注+优惠券+满减
        if (self.type == ShopcartOrderTypeGoods || self.type == ShopcartOrderTypeCart) {
            return self.tableArray[section].shopcart.count*2+2;
        }
        return self.tableArray[section].shopcart.count*2;
    }
    /* 单店铺
    switch (section) {
        case 0:
            return self.tableArray.count+2;
        case 1:
            return 1;
        case 2:
        {
            if ([self.receiptType isEqualToString:@"0"]) { // 不开发票
                return 1;
            } else {
                if ([self.receiptTitle isEqualToString:@"0"]) { // 个人
                    return 3;
                } else {
                    return 4;
                }
            }
        } break;
        case 3:
        {
            if (self.isHaveWorldwide) {
                return 3;
            } else {
                return 0;
            }
        } break;
        default:
            return 0;
    }
    */
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger goodsCount = 0;
    if (indexPath.section < self.tableArray.count) {
        ShopcartClassifyModel *shopModel = self.tableArray[indexPath.section];
        goodsCount = shopModel.shopcart.count;
    }
    
    ShopcartOrderTableViewCell *cell = [ShopcartOrderTableViewCell shopcartOrderCellWith:tableView indexPath:indexPath goodsCount:goodsCount classifyCount:self.tableArray.count];
    if (indexPath.section < self.tableArray.count) {
        ShopcartClassifyModel *shopModel = self.tableArray[indexPath.section];
        if (indexPath.row < shopModel.shopcart.count*2+2) {
            ShopcartModel *model;
            if (indexPath.row < shopModel.shopcart.count*2) {
                model = shopModel.shopcart[indexPath.row/2];
            }
            [cell updateGoodCellWith:model classifyModel:shopModel indexPath:indexPath goodsCount:shopModel.shopcart.count classifyCount:self.tableArray.count];
            cell.noteBlock = ^(NSString *note) {
                //NSLog(@"section - %ld, row - %ld",indexPath.section,indexPath.row);
                model.note = note;
            };
        }
    }
    /*
    if (indexPath.section == 0 && indexPath.row < self.tableArray.count) {
        ShopcartModel *model = shopModel.shopcart[indexPath.row/2];
        [cell updateGoodCellWith:model classifyModel:shopModel indexPath:indexPath goodsCount:shopModel.shopcart.count classifyCount:self.tableArray.count];
    }
     */
    [self updateCellIndexPath:indexPath cell:cell];
    
    [cell.seventhTextField setDelegate:self];
    //[cell.fourthTextView setDelegate:self];
    
    __block typeof(self) blockSelf = self;
    cell.block = ^(ShopcartOrderClickType type) {
        switch (type) {
            case ShopcartOrderClickTypeReceipt:
            {
                [blockSelf receiptButtonAction];
            } break;
            case ShopcartOrderClickTypeEnterprise:
            {
                [blockSelf enterpriseButtonAction];
            } break;
            case ShopcartOrderClickTypePerson:
            {
                [blockSelf personalButtonAction];
            } break;
            case ShopcartOrderClickTypeFront:
            {
                [blockSelf chooseIDCardImage:ShopcartOrderClickTypeFront];
            } break;
            case ShopcartOrderClickTypeBack:
            {
                [blockSelf chooseIDCardImage:ShopcartOrderClickTypeBack];
            } break;
            default:
                break;
        }
    };
    return cell;
}
- (void)updateCellIndexPath:(NSIndexPath *)indexPath cell:(ShopcartOrderTableViewCell *)cell {
    NSInteger classifyCount = self.tableArray.count;
    if (indexPath.section == classifyCount) {
        // 邮费
        [cell.thirdPriceLabel setText:[self getPostage]];
    } else if (indexPath.section == classifyCount+1) {
        // 发票
        switch (indexPath.row) {
            case 0:
            {
                // 发票类型 0不开发票 1普通发票
                if ([self.receiptType isEqualToString:@"0"]) {
                    [cell.fifthTypeButton setTitle:@"不开发票" forState:UIControlStateNormal];
                } else {
                    [cell.fifthTypeButton setTitle:@"普通发票" forState:UIControlStateNormal];
                }
            } break;
            case 1:
            {
                // 发票抬头 0个人 1企业
                if ([self.receiptTitle isEqualToString:@"0"]) {
                    [cell.sixthPersonButton setSelected:YES];
                    [cell.sixthEnterpriseButton setSelected:NO];
                } else {
                    [cell.sixthPersonButton setSelected:NO];
                    [cell.sixthEnterpriseButton setSelected:YES];
                }
            } break;
            case 2:
            {
                // 发票姓名
                self.nameTextField = cell.seventhTextField;
                // 发票抬头 0个人 1企业
                if ([self.receiptTitle isEqualToString:@"0"]) {
                    [cell.seventhTitleLabel setText:@"添加姓名："];
                    [cell.seventhTextField setPlaceholder:@"请填写姓名"];
                } else {
                    [cell.seventhTitleLabel setText:@"添加名称："];
                    [cell.seventhTextField setPlaceholder:@"请填写名称"];
                }
            } break;
            case 3:
            {
                // 发票税号
                self.numberTextField = cell.seventhTextField;
                [cell.seventhTitleLabel setText:@"添加税号："];
                [cell.seventhTextField setPlaceholder:@"必填，请填写纳税人识别号"];
            } break;
            default:
                break;
        }
    } else if (indexPath.section == classifyCount+2) {
        // 身份证
        switch (indexPath.row) {
            case 0:
            {
                // 真实姓名
                self.IDCardNameTextField = cell.seventhTextField;
                [cell.seventhTitleLabel setText:@"真实姓名"];
                [cell.seventhTextField setPlaceholder:@"请输入与身份证一致的姓名"];
            } break;
            case 1:
            {
                // 身份证号
                self.IDCardNumberTextField = cell.seventhTextField;
                [cell.seventhTitleLabel setText:@"身份证号"];
                [cell.seventhTextField setPlaceholder:@"请输入身份证号"];
            } break;
            case 2:
            {
                // 正反照
                if (self.IDCardFrontImage) {
                    [cell.eighthFrontImageView setImage:self.IDCardFrontImage];
                }
                if (self.IDCardBackImage) {
                    [cell.eighthBackImageView setImage:self.IDCardBackImage];
                }
            } break;
            default:
                break;
        }
    }
    /* 单店铺
    NSInteger count = self.tableArray.count;
    switch (indexPath.section) {
        case 0:
        {
            if (indexPath.row == count) {
                
            } else if (indexPath.row == count+1) {
                // 邮费
                [cell.thirdPriceLabel setText:[self getPostage]];
            }
        } break;
        case 1:
        {
            // 备注
            self.remarksTextView = cell.fourthTextView;
        } break;
        case 2:
        {
            switch (indexPath.row) {
                case 0:
                {
                    // 发票类型 0不开发票 1普通发票
                    if ([self.receiptType isEqualToString:@"0"]) {
                        [cell.fifthTypeButton setTitle:@"不开发票" forState:UIControlStateNormal];
                    } else {
                        [cell.fifthTypeButton setTitle:@"普通发票" forState:UIControlStateNormal];
                    }
                } break;
                case 1:
                {
                    // 发票抬头 0个人 1企业
                    if ([self.receiptTitle isEqualToString:@"0"]) {
                        [cell.sixthPersonButton setSelected:YES];
                        [cell.sixthEnterpriseButton setSelected:NO];
                    } else {
                        [cell.sixthPersonButton setSelected:NO];
                        [cell.sixthEnterpriseButton setSelected:YES];
                    }
                } break;
                case 2:
                {
                    // 发票姓名
                    self.nameTextField = cell.seventhTextField;
                    // 发票抬头 0个人 1企业
                    if ([self.receiptTitle isEqualToString:@"0"]) {
                        [cell.seventhTitleLabel setText:@"添加姓名："];
                        [cell.seventhTextField setPlaceholder:@"请填写姓名"];
                    } else {
                        [cell.seventhTitleLabel setText:@"添加名称："];
                        [cell.seventhTextField setPlaceholder:@"请填写名称"];
                    }
                } break;
                case 3:
                {
                    // 发票税号
                    self.numberTextField = cell.seventhTextField;
                    [cell.seventhTitleLabel setText:@"添加税号："];
                    [cell.seventhTextField setPlaceholder:@"必填，请填写纳税人识别号"];
                } break;
                default:
                    break;
            }
        } break;
        case 3: // 全球购
        {
            switch (indexPath.row) {
                case 0:
                {
                    // 真实姓名
                    self.IDCardNameTextField = cell.seventhTextField;
                    [cell.seventhTitleLabel setText:@"真实姓名"];
                    [cell.seventhTextField setPlaceholder:@"请输入与身份证一致的姓名"];
                } break;
                case 1:
                {
                    // 身份证号
                    self.IDCardNumberTextField = cell.seventhTextField;
                    [cell.seventhTitleLabel setText:@"身份证号"];
                    [cell.seventhTextField setPlaceholder:@"请输入身份证号"];
                } break;
                case 2:
                {
                    // 正反照
                    if (self.IDCardFrontImage) {
                        [cell.eighthFrontImageView setImage:self.IDCardFrontImage];
                    }
                    if (self.IDCardBackImage) {
                        [cell.eighthBackImageView setImage:self.IDCardBackImage];
                    }
                } break;
                default:
                    break;
            }
        } break;
        default:
            break;
    }
     */
}
- (NSString *)getPostage {
    if (!self.isScope) {
        return @"无法配送";
    }
    if (self.postageStr.doubleValue == 0) {
        return @"包邮";
    }
    return [NSString stringWithFormat:@"¥%@",self.postageStr];
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger classifyCount = self.tableArray.count;
    if (indexPath.section < classifyCount) {
        ShopcartClassifyModel *shopModel = self.tableArray[indexPath.section];
        NSInteger count = shopModel.shopcart.count;
        //ShopcartModel *model = shopModel.shopcart[indexPath.row/2];
        // 商品+备注+优惠券+满减
        if (indexPath.row == count*2) {
            // 优惠券
            __block typeof(self) blockSelf = self;
            CouponViewController *couponVC = [[CouponViewController alloc] init];
            //MARK:测试            
            if (self.type == ShopcartOrderTypeCart) {
                couponVC.type = CouponFromTypeShopcartOrder;
                couponVC.ids = [self getScidsWith:shopModel];
            } else {
                couponVC.type = CouponFromTypeGoodsOrder;
                couponVC.ids = self.tableArray.firstObject.shopcart.firstObject.gid;
                couponVC.number = self.tableArray.firstObject.shopcart.firstObject.number;
            }
            couponVC.block = ^(CouponModel *model) {
                blockSelf.tableArray[indexPath.section].couponModel = model;
                [blockSelf.tableView reloadData];
                [blockSelf updateUI];
            };
            [self.navigationController pushViewController:couponVC animated:YES];
        } else if (indexPath.row == count*2+1) {
            // 满减（同优惠券）
            
        } else if (indexPath.row%2 == 0) {
            NSLog(@"点击商品了");
        } else if (indexPath.row%2 == 1) {
            // 备注
            
        }
    }
    /* 单店铺
    switch (indexPath.section) {
        case 0:
        {
            if (indexPath.row < self.tableArray.count) {
                NSLog(@"点击商品了");
            }
            if (indexPath.row == self.tableArray.count) {
                __block typeof(self) blockSelf = self;
                CouponViewController *couponVC = [[CouponViewController alloc] init];
                //MARK:测试
                couponVC.gcid = @"2";
                couponVC.type = CouponFromTypeShopcartOrder;
                couponVC.block = ^(CouponModel *model) {
                    blockSelf.tableArray[indexPath.section].couponModel = model;
                    [blockSelf.tableView reloadData];
                };
                [self.navigationController pushViewController:couponVC animated:YES];
            }
        } break;
            
        default:
            break;
    }
     */
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger classifyCount = self.tableArray.count;
    
    
    if (indexPath.section == classifyCount) {
        // 邮费
        if (self.type == ShopcartOrderTypeNearby) {
            return 0;
        }
        return 44;
    } else if (indexPath.section == classifyCount+1) {
        // 发票
        switch (indexPath.row) {
            case 0:
            {
                return 44;
            } break;
            case 1:
            {
                return 44;
            } break;
            case 2: case 3:
            {
                return 44;
            } break;
            default:
                break;
        }
    } else if (indexPath.section == classifyCount+2) {
        // 身份证
        switch (indexPath.row) {
            case 0: case 1:
            {
                return 44;
            } break;
            case 2:
            {
                return 367;
            } break;
            default:
                break;
        }
    } else {
        ShopcartClassifyModel *shopModel = self.tableArray[indexPath.section];
        NSInteger count = shopModel.shopcart.count;
        // 商品+备注+优惠券+满减
        if (indexPath.row == count*2) {
            if (self.type == ShopcartOrderTypeGoods || self.type == ShopcartOrderTypeCart) {
                return 44;
            }
            return 0;
        } else if (indexPath.row == count*2+1) {
            if (self.type == ShopcartOrderTypeGoods || self.type == ShopcartOrderTypeCart) {
                return 44;
            }
            return 0;
        } else if (indexPath.row%2 == 0) {
            return 112;
        } else if (indexPath.row%2 == 1) {
            return 100;
        }
    }
    return 0;
    /* 单店铺
    NSInteger count = self.tableArray.count;
    switch (indexPath.section) {
        case 0:
        {
            if (indexPath.row < count) {
                return 112;
            } else if (indexPath.row == count) {
                return 44;
            } else {
                return 44;
            }
        } break;
        case 1:
        {
            return 100;
        } break;
        case 2:
        {
            switch (indexPath.row) {
                case 0:
                {
                    return 44;
                } break;
                case 1:
                {
                    return 44;
                } break;
                case 2: case 3:
                {
                    return 44;
                } break;
                default:
                    break;
            }
        } break;
        case 3:
        {
            switch (indexPath.row) {
                case 0: case 1:
                {
                    return 44;
                } break;
                case 2:
                {
                    return 367;
                } break;
                default:
                    break;
            }
        } break;
        default:
            break;
    }
     return 0;
     */
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    // 单店铺没有 self.tableArray.count+
    if (!self.isHaveWorldwide) {
        if (self.type == ShopcartOrderTypeIntegral) {
            if (section < self.tableArray.count) {
                return 10;
            }
            return 1;
        }
        if (section < self.tableArray.count+1) {
            return 10;
        }
        return 1;
    }
    if (section < self.tableArray.count+2) {
        return 10;
    }
    return 1;
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
#pragma mark - 系统相册和相机
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary*)info{
    
    
    UIImage *image = (UIImage *)[info objectForKey:@"UIImagePickerControllerEditedImage"];
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);//把图片存到图片库
    }
    
    //关闭图片选择器
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if (self.IDCardImageType == ShopcartOrderClickTypeFront) {
        self.IDCardFrontImage = image;
        [self.tableView reloadData];
        self.IDCardImageType = -1;
    }
    if (self.IDCardImageType == ShopcartOrderClickTypeBack) {
        self.IDCardBackImage = image;
        [self.tableView reloadData];
        self.IDCardImageType = -1;
    }
    
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
